<template>
  <div>
    <div class="content-item">
      <p>
        <span>评比名称：{{rateInfo.name}}[{{formatRate('', '', rateInfo.rateType, '')}}]</span>
        <span class="gtextlink"
              @click="toDetail">详情</span>
      </p>
      <p>
        <span>评比时间：{{formatTime('', '', rateInfo.startAt, '')}}至{{formatTime('', '', rateInfo.endAt, '')}}</span>
        <span> 开展校区：{{schoolAreaName.join('、')}}</span>
      </p>
      <p>
        <strong>评比名单</strong>
      </p>
      <p v-if="statisticsData.starLevelCount"
         style="cursor: pointer;">
        <strong>寝室星级</strong>
        <span @click="changeStar(null)"
              :class="{gtextlinkred: starLevel === 'level-null'}">全部({{statisticsData.starLevelCount.starLevelTotal}})</span>
        <span @click="changeStar(1)"
              :class="{gtextlinkred: starLevel === 'level-1'}">一星寝室({{statisticsData.starLevelCount.starLevel_1}})</span>
        <span @click="changeStar(2)"
              :class="{gtextlinkred: starLevel === 'level-2'}">二星寝室({{statisticsData.starLevelCount.starLevel_2}})</span>
        <span @click="changeStar(3)"
              :class="{gtextlinkred: starLevel === 'level-3'}">三星寝室({{statisticsData.starLevelCount.starLevel_3}})</span>
        <span @click="changeStar(4)"
              :class="{gtextlinkred: starLevel === 'level-4'}">四星寝室({{statisticsData.starLevelCount.starLevel_4}})</span>
        <span @click="changeStar(5)"
              :class="{gtextlinkred: starLevel === 'level-5'}">五星寝室({{statisticsData.starLevelCount.starLevel_5}})</span>
      </p>
      <p v-if="statisticsData.dataFromCount && (rateStatus === 1 || rateStatus === 2)"
         style="cursor: pointer;">
        <strong>名单来源</strong>
        <span @click="changeFrom(null)"
              :class="{gtextlinkred: dataFrom === 'from-null'}">全部({{statisticsData.dataFromCount.dataFromTotal}})</span>
        <span @click="changeFrom(1)"
              :class="{gtextlinkred: dataFrom === 'from-1'}">系统({{statisticsData.dataFromCount.dataFromSys}})</span>
        <span @click="changeFrom(2)"
              :class="{gtextlinkred: dataFrom === 'from-2'}">导入({{statisticsData.dataFromCount.dataFromImport}})</span>
      </p>
      <div>
        <el-input size="small"
                  placeholder="输入房间号"
                  style="width: 220px;"
                  v-model="queryParams.name" />
        <el-button size="small"
                   type="primary"
                   @click="query()">搜索</el-button>
        <div style="display: inline-block;"
             v-if="(rateStatus === 1 || rateStatus === 2) && userInfo.roleName === '学校用户'">
          <el-button size="small"
                     @click="publicity">结果公示</el-button>
          <el-button size="small"
                     @click="oneKeyLock(1)">一键锁定</el-button>
          <el-button size="small"
                     @click="oneKeyLock(0)">一键解锁</el-button>
        </div>
        <div style="display: inline-block;"
             v-if="(rateStatus === 1 || rateStatus === 2) && (userInfo.roleName === '学校用户' || userInfo.roleName === '学院用户')">
          <el-button size="small"
                     @click="importRoll">名单导入</el-button>
          <a class="g-button"
             href=".././templet/ratinglist_templet.xls">模板下载</a>
        </div>
      </div>
    </div>
    <div class="content-item">
      <el-table :data="tableData"
                v-if="rateStatus === 1 || rateStatus === 2"
                class="table-header-gray">
        <el-table-column label="校区"
                         prop="shoolArea">
        </el-table-column>
        <el-table-column label="园区"
                         prop="campusArea">
        </el-table-column>
        <el-table-column label="楼栋"
                         prop="building">
        </el-table-column>
        <el-table-column label="寝室"
                         prop="bedroomName">
        </el-table-column>
        <el-table-column label="卫生得分"
                         v-if="rateType === 1"
                         prop="healthScore">
        </el-table-column>
        <el-table-column label="平均学分绩点"
                         v-else
                         prop="avgPoint">
        </el-table-column>
        <el-table-column label="违章次数"
                         prop="violateCount">
        </el-table-column>
        <el-table-column label="当前等级"
                         :formatter="formatStart"
                         v-if="rateType === 1"
                         prop="currentLevel">
        </el-table-column>
        <el-table-column label="星级等级"
                         :formatter="formatStart"
                         v-else
                         prop="currentLevel">
        </el-table-column>
        <el-table-column label="评后等级"
                         v-if="rateType === 1">
          <template slot-scope="scope">
            <el-select v-model="scope.row.afterLevel"
                       @change="modifyRatingListLevelUsingPUT(scope.row.id, scope.row.afterLevel)"
                       size="small">
              <el-option v-for="(item, index) in starLevels"
                         :value="item.value"
                         :label="item.name"
                         :key="index"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="数据来源"
                         :formatter="formatDataForm"
                         prop="dataFrom">
        </el-table-column>
        <el-table-column label="是否选择">
          <template slot-scope="scope">
            <switch-vue :isActive="Boolean(scope.row.isSelect)"
                        @switchChange="updateSelectUsingPUT(scope.row.id, scope.row.isSelect)" />
          </template>
        </el-table-column>
        <el-table-column label="是否锁定"
                         v-if="userInfo.roleName === '学校用户'">
          <template slot-scope="scope">
            <span v-if="scope.row.status === 0"
                  class="gtextlink"
                  @click="modify(scope.row.id, 'status', 1)">锁定</span>
            <span v-else
                  class="gtextlink"
                  @click="modify(scope.row.id, 'status', 0)">解锁</span>
          </template>
        </el-table-column>
      </el-table>
      <el-table :data="tableData"
                v-if="rateStatus === 3 || rateStatus === 4"
                class="table-header-gray">
        <el-table-column label="校区"
                         prop="shoolArea">
        </el-table-column>
        <el-table-column label="园区"
                         prop="campusArea">
        </el-table-column>
        <el-table-column label="楼栋"
                         prop="building">
        </el-table-column>
        <el-table-column label="寝室"
                         prop="bedroomName">
        </el-table-column>
        <el-table-column label="卫生得分"
                         v-if="rateType === 1"
                         prop="healthScore">
        </el-table-column>
        <el-table-column label="平均学分绩点"
                         v-else
                         prop="avgPoint">
        </el-table-column>
        <el-table-column label="违章次数"
                         prop="violateCount">
        </el-table-column>
        <el-table-column label="当前等级"
                         :formatter="formatStart"
                         v-if="rateType === 1"
                         prop="afterLevel">
        </el-table-column>
        <el-table-column label="星级等级"
                         :formatter="formatStart"
                         v-else
                         prop="afterLevel">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <span @click="toDorm(scope.row)"
                  class="gtextlink">查看</span>
          </template>
        </el-table-column>
      </el-table>
      <pagenation :dataLength="total"
                  :page="queryParams.page"
                  :pageSize="queryParams.size"
                  :handleSizeChange="handleSizeChange"
                  :handleCurrentChange="handleCurrentChange" />
      <dialog-upload :target="uploadTarget"
                     :dialogShow="dialogShow"
                     :successUploadCallback="successUploadCallback"
                     :fileList="fileList"
                     :handleClose="handleClose" />
    </div>
  </div>
</template>
<script>
import { updateSelectUsingPUT, modifyRatingListLevelUsingPUT, modefyRatingStatusUsingPUT, updataAllRatingListStatusUsingPUT, countRatingListUsingGET, findRatingListUsingPOST, modifyRatingListUsingPUT, listSchoolAreaUsingGET } from '@api/auto'
import { formatTool, pagination, config } from '@/tools/mixin'
import { downExl } from '@/tools/utils'
import dialogUpload from './dialog'
export default {
  name: '',
  props: {
  },
  mixins: [formatTool, pagination, config],
  components: {
    dialogUpload
  },
  data () {
    return {
      dialogShow: false,
      rateInfo: {},
      schoolAreaName: [],
      fileList: [],
      statisticsData: {},
      total: 0,
      queryParams: {
        page: 1,
        size: 10,
        ratingId: null,
        name: null,
        starLevel: null,
        dataFrom: null
      },
      tableData: [],
      rateType: 1,
      rateStatus: 1,
      starLevel: 'level-null',
      dataFrom: 'from-null',
      uploadTarget: '',
      userInfo: null
    }
  },
  created () {
    this.userInfo = JSON.parse(sessionStorage.userInfo)
    this.rateInfo = JSON.parse(sessionStorage.rateInfo) || {}
    let schoolAreas = []
    listSchoolAreaUsingGET().then(res => {
      schoolAreas = res.data
      this.schoolAreaName = this.rateInfo.schoolAreas.map(item => {
        let res = schoolAreas.find(ele => {
          return ele.id === item
        })
        return res.name
      })
    })

    this.queryParams.ratingId = this.rateInfo.id
    this.uploadTarget = '.././api/bedroomRating/importList/' + this.rateInfo.id
    this.rateType = this.rateInfo.rateType
    this.rateStatus = this.rateInfo.status
  },
  mounted () {
    this.countRatingListUsingGET()
    this.query()
  },
  methods: {
    // 寝室风貌
    toDorm (data) {
      this.$router.push({
        path: '/main/dormManage/dormRate/dormView',
        query: {
          roomId: data.bedroomId,
          date: data.createAt,
          id: data.id
        }
      })
    },
    // 跳转查看详情
    toDetail () {
      let obj = {
        content: this.rateInfo.description,
        name: this.rateInfo.name,
        type: this.formatRate('', '', this.rateInfo.rateType, ''),
        time: `${this.formatTime('', '', this.rateInfo.startAt, '')}至${this.formatTime('', '', this.rateInfo.endAt, '')}`,
        schoolAreas: this.rateInfo.schoolAreas
      }
      sessionStorage.richText = JSON.stringify(obj)
      this.$router.push({
        path: '/main/dormManage/dormRate/detail'
      })
    },
    // 分页条件查询名单
    query (pageNum = 1) {
      this.queryParams.page = pageNum
      findRatingListUsingPOST(this.queryParams)
        .then(res => {
          this.total = (res.data && res.data.total) || 0
          this.tableData = (res.data && res.data.list) || []
        })
    },
    // 统计查询
    countRatingListUsingGET () {
      countRatingListUsingGET(this.rateInfo.id)
        .then(res => {
          this.statisticsData = res.data
        })
    },
    // 修改名单状态
    modify (id, k, v) {
      let params = {
        id: id
      }
      params[k] = v
      modifyRatingListUsingPUT(params)
        .then(() => {
          this.$message.success('操作成功')
          this.query()
        })
        .catch(() => {
          this.query()
        })
    },
    // 编辑寝室评比名单等级
    modifyRatingListLevelUsingPUT (id, level) {
      modifyRatingListLevelUsingPUT(id, level)
        .then(() => {
          this.$message.success('操作成功')
          this.countRatingListUsingGET()
          this.query()
        })
        .catch(() => {
          this.query()
        })
    },
    // 修改选中状态
    updateSelectUsingPUT (id, flag) {
      let v = flag === 0 ? 1 : 0
      updateSelectUsingPUT(id, v)
        .then(() => {
          this.$message.success('操作成功')
          this.countRatingListUsingGET()
          this.query()
        })
        .catch(() => {
          this.query()
        })
    },
    // 切换开关
    switchChange (id, isSelect) {
      let v = isSelect === 0 ? 1 : 0
      this.modify(id, 'isSelect', v)
    },
    // 一键锁定/解锁
    oneKeyLock (status) {
      updataAllRatingListStatusUsingPUT(this.rateInfo.id, status)
        .then(() => {
          this.$message.success('操作成功')
          this.query()
        })
    },
    changeStar (v) {
      this.starLevel = `level-${v}`
      this.queryParams.starLevel = v
      this.query()
    },
    changeFrom (v) {
      this.dataFrom = `from-${v}`
      this.queryParams.dataFrom = v
      this.query()
    },
    publicity () {
      // 通过评比id公示
      this.$confirm('是否确认公示本次评比结果？', '公示确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        modefyRatingStatusUsingPUT(this.queryParams.ratingId)
          .then(() => {
            this.$message.success('公示成功')
            this.$router.push({
              path: '/main/dormManage/dormRate/list'
            })
          })
      })
    },
    importRoll () {
      this.dialogShow = true
    },
    handleClose () {
      this.dialogShow = false
      this.fileList = []
    },
    successUploadCallback (e) {
      this.fileList = []
      this.dialogShow = false
      if (e.status) {
        if (!e.data) {
          this.$message.success('导入成功')
          this.query()
          this.countRatingListUsingGET()
        } else {
          if (e.data) {
            downExl(e.data, '失败名单.xls', false)
          }
          this.query()
          this.countRatingListUsingGET()
          this.fileList = []
          this.$message.warning('存在导入失败文件')
        }
      } else {
        this.$message.error(e.message)
      }
    }
  }
}
</script>
<style lang='less' scoped>
</style>
